package com.tangji.signaltower.websocket.netty;

import com.tangji.signaltower.websocket.session.ServerSession;
import com.tangji.signaltower.websocket.session.SessionFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created with IntelliJ IDEA.
 * User: Amarendar
 * Date: 2020/6/17
 * Time: 下午4:54
 */
public class HeartBeatServerHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(HeartBeatServerHandler.class);

    /**
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                logger.info("已经30秒未收到客户端的消息了,主动断开客户端连接,{}", ctx.channel().remoteAddress());
                ServerSession serverSession = ServerSession.getSession(ctx);
                if (serverSession != null) {
                    SessionFactory.removeFromAllMap(serverSession);
                }
                ctx.channel().close();
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
